import React, { PropsWithChildren, useState, useEffect } from 'react';
import { connect } from 'react-redux';
import classnames from 'classnames';
import './index.scss';
import LoginPanel from './components/loginPanel'
import RegisterPanel from './components/registerPanel'
import { StoreState, LoginState } from '../../store/reducers'
import * as actions from '../../store/actions/login'
import { getValidateCode, validate } from '../../api/login'
import { getResponseData } from '../../utils/helpers';
import { BaseResponse, GetValidateResponseData } from '../../api/types';
// 仓库的状态和派发的action
type LoginProps = LoginState & typeof actions
// 最终的组件的props
type Props = PropsWithChildren<LoginProps>
// 登录
function Login(props: Props) {
    // 验证码图片信息
    const [codeUrl, setCodeUrl] = useState<string>('');
    const [randonNum, setRandonNum] = useState<number>(0);
    useEffect(() => {
        (async () => {
            // 请求验证码
            const res = getResponseData<GetValidateResponseData>(await getValidateCode());
            // 获取成功
            if (res.code === 1) {
                // 设置图片路径
                setCodeUrl(res.data.svg);
            }
        })()
    }, [randonNum])

    // 验证登录信息 只执行一次
    useEffect(() => {
        (async () => {
            const res = getResponseData<BaseResponse>(await validate());
            if (res.code === 1) {
                // 如果已经登录了, 跳转到首页   
                props.go('/');
            } else {
                // 清理掉session和store中已经登录的信息
                props.logout();
            }
        })()
    }, [])
    return <div className="login fx-c">
        <div className={classnames(['wrapper', { "animate": !props.isLoginState }])}>
            <div className="login-panel clearfix clearfix">
                <LoginPanel />
                <RegisterPanel codeUrl={codeUrl} refreshCode={setRandonNum} />
            </div>
        </div>
    </div>
}
const mapStateToProps = (state: StoreState): LoginState => state.login

export default connect(mapStateToProps, actions)(Login);
